/**
 * Created by Sergey on 20.11.13.
 */

/**
 * Fix last opened content widget
 * */
var lastOpenedContentWidget = null;

/**
 * Control hiding when activate hiding after timeout
 */
var needHideContentWidget = false;

/**
 * Main method for creating menu
 * @param selector
 */
function createMenu(selector) {
    var menus = $(selector);
    menus.each(function () {
        modifyMenu($(this));
        hideContent($(this).find('.menu-content'));
        contentAppearance($(this));
    });
}

/**
 * Add classes to element of menu for mark it
 * @param menu
 */
function modifyMenu(menu) {
    menu.find('li').each(function () {
        var item = $(this);
        item.children().first().addClass('menu-title');
        var content = item.children(':nth-child(2)');
        if (content.length > 0) {
            item.addClass('has-content');
            content.addClass('widget');
            content.addClass('menu-content');
        }
    });
}

/**
 * Run hiding widget after timeout
 * @param contentWidget
 * @param delay
 */
function hideContentAfter(contentWidget, delay) {
    setTimeout(function () {
        if (needHideContentWidget) {
            hideContent(contentWidget);
        }
    }, delay);
}

/**
 * Hide content right now
 * @param contentWidget
 */
function hideContent(contentWidget) {
    needHideContentWidget = false;
    contentWidget.hide();
}

/**
 * Control content appearance
 * @param menu
 */
function contentAppearance(menu) {
    var itemsWithContent = menu.children().filter('li.has-content');
    itemsWithContent.hover(
        function () {
            var contentWidget = $(this).find('.menu-content');
            contentWidget.hover(
                function () {
                    needHideContentWidget = false
                },
                function () {
                    needHideContentWidget = true
                }
            );

            if (lastOpenedContentWidget != null && lastOpenedContentWidget != contentWidget) {
                hideContent(lastOpenedContentWidget);
            }
            lastOpenedContentWidget = contentWidget;

            contentWidget.show().position({
                my: "left top-10",
                at: "right top",
                of: $(this)
            });
        },
        function () {
            needHideContentWidget = true;
            hideContentAfter($(this).find('.menu-content'), 500);
        }
    );
}

/**
 * Root method - handle document creation finished
 */
$(function () {
    createMenu('.menu');
});